package m2;

import com.rabbitmq.client.*;
import sun.java2d.opengl.OGLSurfaceData;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory f = new ConnectionFactory();
        f.setHost("192.168.64.140");
        f.setPort(5672);
        f.setUsername("admin");
        f.setPassword("admin");
        Connection con = f.newConnection();
        Channel c = con.createChannel();

        c.queueDeclare("task_queue", true, false, false , null);

        DeliverCallback deliverCallback = (consumerTag, message) -> {
            String s = new String(message.getBody());
            System.out.println("收到：" + s);
            //模拟处理耗时消息
            //遍历所有字符，找到“.”字符，每找到一个暂停1秒
            for (int i = 0; i < s.length(); i++) {
                if ('.' == s.charAt(i)) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }
            System.out.println("------------------------消息处理完成");

            //手动发送回执，是否同时确认以前
            c.basicAck(message.getEnvelope().getDeliveryTag(), false);
            c.basicQos(1);
        };

        CancelCallback cancelCallback = (consumerTag) -> {

        };

        c.basicConsume("helloworld", false,deliverCallback,cancelCallback);


    }
}
